#pragma once
#include <iostream>
#include <thread>
#include <functional>

namespace ThreadModule
{
    static int number = 1;
    using func_t = std::function<void()>;
    class Thread
    {

        void EnableRuning()
        {
            _isruning = true;
        }
        void EnableDetach()
        {
            _isdetach = true;
        }
        static void* Routine(void* args)
        {
            Thread* self = static_cast<Thread*>(args);
            self->EnableRuning();
            if(self->_isdetach)//如果外部不手动分离，这里就一直是false
                self->Detach();//Detach的内部逻辑不允许重复分离
            pthread_setname_np(self->_tid,self->_name.c_str());
            self->_func();
            return nullptr;
        }
    public:
        Thread(func_t func)
            : _tid(0),
              _isdetach(false),
              _isruning(false),
              _func(func),
              _res(nullptr)
        {
            _name += "Thread-" + std::to_string(number++);
        }
        void Detach()
        {
            if(_isdetach)
                return;
            if(_isruning)//正在运行的话就去分离线程
                pthread_detach(_tid);
            EnableDetach();
        }
        bool Start()
        {
            if(_isruning)
                return false;
            int n = pthread_create(&_tid,nullptr,Routine,this);
            if (n != 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        bool Stop()
        {
            if(_isruning)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                {
                    return false;
                }
                else
                {
                    _isruning = false;
                    return true;
                }
            }
        }
        void Join()
        {
            if(_isdetach)
                return;
            int n = pthread_join(_tid,&_res);
            (void)n;
        }
        pthread_t GetTid()
        {
            return _tid;
        }
        std::string GetName()
        {
            return _name;
        }

        ~Thread()
        {
        }

    private:
        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isruning;
        func_t _func;

        void* _res;
    };
}